﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ScanCode;
using ZBar;
using Image = System.Drawing.Image;

namespace AutoID.APP.LookCode
{
    public class BarCode
    {
        /// <summary>
        /// 条码识别
        /// 此方式只在windows平台可支持
        /// </summary>
        public static List<ScanSymbol> ScanBarCode(string filename)
        {
            using (var bitmap = (Bitmap)Image.FromFile(filename))
            {
                return ScanBarCode(bitmap);
            }
        }

        /// <summary>
        /// 条码识别
        /// 此方式只在windows平台可支持
        /// </summary>
        public static List<ScanSymbol> ScanBarCode(Bitmap bitmap)
        {
            bitmap = MakeGrayscale3(bitmap);
            var result = new List<ScanSymbol>();
            using (var scanner = new ImageScanner())
            {
                List<Symbol> symbols = scanner.Scan(bitmap);
                if (symbols != null && symbols.Count > 0)
                {
                    result = symbols.Select(ScanSymbol.CreateSymbol).ToList();
                }
            }
            return result;
        }





        /// <summary>
        /// 处理图片灰度
        /// </summary>
        private static Bitmap MakeGrayscale3(Bitmap original)
        {
            //create a blank bitmap the same size as original
            Bitmap newBitmap = new Bitmap(original.Width, original.Height);
            //get a graphics object from the new image
            Graphics g = Graphics.FromImage(newBitmap);
            //create the grayscale ColorMatrix
            System.Drawing.Imaging.ColorMatrix colorMatrix = new ColorMatrix(
                new float[][]
                {
            new float[] {.3f, .3f, .3f, 0, 0},
            new float[] {.59f, .59f, .59f, 0, 0},
            new float[] {.11f, .11f, .11f, 0, 0},
            new float[] {0, 0, 0, 1, 0},
            new float[] {0, 0, 0, 0, 1}
              });
            //创建一些图像属性
            ImageAttributes attributes = new ImageAttributes();
            //设置颜色矩阵属性
            attributes.SetColorMatrix(colorMatrix);
            //在新图像上绘制原始图像
            //使用灰度颜色矩阵
            g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
               0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
            //dispose the Graphics object
            g.Dispose();
            return newBitmap;
        }
    }
}
